package com.heima.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
@Order(0)
public class AuthorizeFilter implements GlobalFilter {
    private static List<String> allowUrls=new ArrayList<>();
    static{
        allowUrls.add("/login/in");
        allowUrls.add("/v2/api-docs");

    }
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        for(String allowUrls:allowUrls){
            if (path.contains(allowUrls)) {
            return chain.filter(exchange);
            }
        }
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isBlank(token)) {
            return writeMessage(exchange,"请登录后在访问");
        }
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            int i = AppJwtUtil.verifyToken(claimsBody);
            if(i<1){
                Object id = claimsBody.get("id");
                request.mutate().header("userId",String.valueOf(id));
                exchange.mutate().request(request);
                log.info("解析token成功  ==>{}",id);
                return chain.filter(exchange);
            }
            log.error("解析token出现异常  ==>token已过期");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("解析token出现异常  ==>{}",e.getMessage());
        }

        return writeMessage(exchange,"解析用户失败，请重新登录");
    }

    private Mono<Void> writeMessage(ServerWebExchange exchange, String msg) {
        Map map =new HashMap<>();
        map.put("code","401");
        map.put("errorMessage",msg);
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        DataBuffer wrap = response.bufferFactory().wrap(JSON.toJSONBytes(map));
        response.writeWith(Flux.just(wrap));

        return null;
    }
}
